<?php

namespace App\Service\Pay;

use App\Console\Commands\Pay\NsqSubMybankRegister;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Service\BaseService;
use App\Service\Cruise\Mission\MybankInputService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use NSQClient\Exception\PoolMissingSocketException;

class MybankService extends BaseService
{
    private int $userId;

    public function __construct(int $userId)
    {
        $this->userId = $userId;
    }

    public function getCruiseOrderModel(string $outOrderNo = '')
    {
        $templateIds = CruiseTemplateModel
            ::query()
            ->where('sysTemplate', CruiseTemplateModel::SYS_TEMPLATE_OTHER_MYBANK_REGISTER)
            ->pluck('id')
            ->toArray();

        if (!$templateIds) {
            BaseService::throwErr('未配置网商进件模板，请联系总部');
        }

        return CruiseOrderModel::query()
                               ->where('createdByUid', $this->userId)
                               ->whereIn('templateId', $templateIds)
                               ->when($outOrderNo, function ($query) use ($outOrderNo) {
                                   $query->whereRaw("extra -> '$.outOrderNo' = '{$outOrderNo}'");
                               })
                               ->first();
    }

    public function getInput(int $shopId, int $onlyStatus): array
    {
        $cruiseOrder = $this->getCruiseOrderModel();

        if ($onlyStatus) {
            return ['status' => $cruiseOrder->status ?? 0];
        }

        // 第一次进来，没有订单，创建订单
        if (!$cruiseOrder) {

            $templateId = CruiseTemplateModel::getTemplateIdBySysTemplate(CruiseTemplateModel::SYS_TEMPLATE_OTHER_MYBANK_REGISTER);

            DB::beginTransaction();
            $obj = (new MybankInputService(0, $this->userId, $shopId));
            $obj->initOrderInput(false, $templateId);
            DB::commit();

            return $obj->getInputObjectFill();
        }

        // 有订单，直接返回
        return (new MybankInputService($cruiseOrder->id, $this->userId))
            ->getInputObjectFill();
    }

    public function updateInput(string $field, $value): void
    {
        $cruiseOrder = $this->getCruiseOrderModel();

        (new MybankInputService($cruiseOrder->id, $this->userId))
            ->saveUserContentJson($field, $value);
    }

    public function submitInput()
    {
        $cruiseOrder = $this->getCruiseOrderModel();

        (new MybankInputService($cruiseOrder->id, $this->userId))
            ->submitOrder();
    }

    public function finish(string $outOrderNo, int $registerStatus, string $registerFailReason): bool
    {
        $cruiseOrder = $this->getCruiseOrderModel($outOrderNo);
        if (!$cruiseOrder) {
            return false;
        }

        if (in_array($cruiseOrder->status, [CruiseOrderModel::STATUS_COMPLETE, CruiseOrderModel::STATUS_CLOSED])) {
            return true;
        }

        // 成功
        if ($registerStatus == NsqSubMybankRegister::REGISTER_STATUS_1) {
            $cruiseOrder->status = CruiseOrderModel::STATUS_COMPLETE;
            $cruiseOrder->save();

            return true;
        }

        // 失败
        if ($registerStatus == NsqSubMybankRegister::REGISTER_STATUS_2) {

            $cruiseOrder->status = CruiseOrderModel::STATUS_NOT_MODIFY;

            // 错误信息
            $extra              = $cruiseOrder->extraArr;
            $extra['errorMsg']  = $registerFailReason;
            $cruiseOrder->extra = $extra;
            $cruiseOrder->save();

            return true;
        }

        return false;
    }

    /**
     * 网商银行审核通过，待用户激活
     * @param string $outOrderNo
     * @return bool
     */
    public function mybankAudit(string $outOrderNo, int $preRegisterStatus, string $preRegisterFailReason = '')
    {
        $cruiseOrder = $this->getCruiseOrderModel($outOrderNo);

        if (!$cruiseOrder) {
            return false;
        }

        if (in_array($cruiseOrder->status, [
            CruiseOrderModel::STATUS_COMPLETE,
            CruiseOrderModel::STATUS_CLOSED
        ])) {
            return true;
        }

        // 成功
        if ($preRegisterStatus == NsqSubMybankRegister::PRE_REGISTER_STATUS_1) {
            $cruiseOrder->status = CruiseOrderModel::STATUS_COLLECTED; // 待用户激活
            $cruiseOrder->save();

            return true;
        }

        // 失败
        if ($preRegisterStatus == NsqSubMybankRegister::PRE_REGISTER_STATUS_2) {
            $cruiseOrder->status = CruiseOrderModel::STATUS_NOT_MODIFY;

            // 错误信息
            $extra              = $cruiseOrder->extraArr;
            $extra['errorMsg']  = $preRegisterFailReason;
            $cruiseOrder->extra = $extra;
            $cruiseOrder->save();

            return true;
        }

        return false;
    }

    /**
     * 删除表单
     * @return void
     */
    public function del(): void
    {
        $cruiseOrder = $this->getCruiseOrderModel();
        if (!$cruiseOrder) {
            BaseService::throwErr('未找到网商进件订单');
        }

        $cruiseOrder->isDeleted = 1;
        $cruiseOrder->save();

        Log::info('删除网商进件订单', [
            'userId'  => $this->userId,
            'orderId' => $cruiseOrder->id
        ]);
    }
}
